import svgCaptcha from "svg-captcha";
import md5 from "md5";

export default class extends koahub.controller {

    async _initialize() {
        this.state.theme = '';

    }

    async login() {

        if (this.isPost()) {
            const data = this.post;
            // if (this.session.verify != data.verify.toLowerCase()) {
            //     this.redirect('/admin/public/login?err=' + encodeURI('验证码错误'));
            //     return;
            // }
            const username = data.username;
            const password = md5(data.password);
            // let Administrator = koahub.models['admin/User'];
            // let Administrator = this.models['admin/User'];
            let Administrator = this.model('admin/Administrator');

            let admin = await Administrator.findOne({username: username, password: password, status: 1}).exec();

            if (admin && admin.status) {
                this.session.adminId = admin.id;//admin._id的虚拟属性
                this.session.adminUsername = admin.username;

                // const secret = koahub.configs['middleware']['koahub-jwt']['secret'];
                // // koahub.logger.debug(secret);
                //
                // const jwt = require('jsonwebtoken');
                // const token = jwt.sign({
                //     data: admin.id,
                //     // 设置 token 过期时间
                //     exp: Math.floor(Date.now() / 1000) + (60 * 60), // 60 seconds * 60 minutes = 1 hour
                // }, secret);
                // this.session.token = token;


                this.redirect('/admin/index/index');
            } else {

                if (await Administrator.findOne({username: username}).exec()) {
                    this.redirect('/admin/public/login?err=' + encodeURI('账号密码错误'));
                } else {
                    //自动注册注册帐号
                    let user = new Administrator({username: username, password: password, status: 1});
                    user.save();
                    this.redirect('/admin/public/login?err=' + encodeURI('帐号自动注册成功，重新登陆'));
                }

                this.redirect('/admin/public/login?err=' + encodeURI('账号密码错误'));
            }

        } else {
            await this.render('admin/public/login');
        }
    }

    async verify() {

        const captcha = svgCaptcha.create();

        this.session.verify = captcha.text.toLowerCase();
        this.set('Content-Type', 'image/svg+xml');
        this.view(captcha.data);
    }

    async logout() {
        this.session = null;
        this.redirect('/admin/public/login');
    }

}